package com.cn.shuangzi.loginplugin.common.socialized;

import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import com.alipay.sdk.app.AuthTask;

import java.util.Map;

/**
 * Created by CN on 2017/3/14.
 */

public class AliPayLogin {
    private String authInfo = "";   // 订单信息
    private Activity activity;
    private ThirdLogin.OnThirdLoginResponseListener onThirdLoginResponseListener;
    private static final int SDK_AUTH_FLAG = 0x20;

    public AliPayLogin(Activity activity, String authInfo, ThirdLogin.OnThirdLoginResponseListener onThirdLoginResponseListener) {
        this.activity = activity;
        this.authInfo = authInfo;
        this.onThirdLoginResponseListener = onThirdLoginResponseListener;
    }

    Runnable authRunnable = new Runnable() {
        @Override
        public void run() {
            AuthTask alipayAuth = new AuthTask(activity);
            Map<String, String> result = alipayAuth.authV2(authInfo, true);
            Message msg = new Message();
            msg.what = SDK_AUTH_FLAG;
            msg.obj = result;
            mHandler.sendMessage(msg);
        }
    };

    // 必须异步调用
    public void login() {
        Thread payThread = new Thread(authRunnable);
        payThread.start();
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case SDK_AUTH_FLAG: {
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();

                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                        if (onThirdLoginResponseListener != null){
                            onThirdLoginResponseListener.onSuccess(authResult.getAuthCode());
                        }
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        if (TextUtils.equals(resultStatus, "6001")) {
                            if (onThirdLoginResponseListener != null)
                                onThirdLoginResponseListener.onCancel();
                        } else {
                            if (onThirdLoginResponseListener != null)
                                onThirdLoginResponseListener.onFailed();
                        }
                    }
                    break;
                }
            }
        }
    };

    public class AuthResult {

        private String resultStatus;
        private String result;
        private String memo;
        private String resultCode;
        private String authCode;
        private String alipayOpenId;

        public AuthResult(Map<String, String> rawResult, boolean removeBrackets) {
            if (rawResult == null) {
                return;
            }

            for (String key : rawResult.keySet()) {
                if (TextUtils.equals(key, "resultStatus")) {
                    resultStatus = rawResult.get(key);
                } else if (TextUtils.equals(key, "result")) {
                    result = rawResult.get(key);
                } else if (TextUtils.equals(key, "memo")) {
                    memo = rawResult.get(key);
                }
            }

            String[] resultValue = result.split("&");
            for (String value : resultValue) {
                if (value.startsWith("alipay_open_id")) {
                    alipayOpenId = removeBrackets(getValue("alipay_open_id=", value), removeBrackets);
                    continue;
                }
                if (value.startsWith("auth_code")) {
                    authCode = removeBrackets(getValue("auth_code=", value), removeBrackets);
                    continue;
                }
                if (value.startsWith("result_code")) {
                    resultCode = removeBrackets(getValue("result_code=", value), removeBrackets);
                    continue;
                }
            }

        }

        private String removeBrackets(String str, boolean remove) {
            if (remove) {
                if (!TextUtils.isEmpty(str)) {
                    if (str.startsWith("\"")) {
                        str = str.replaceFirst("\"", "");
                    }
                    if (str.endsWith("\"")) {
                        str = str.substring(0, str.length() - 1);
                    }
                }
            }
            return str;
        }

        @Override
        public String toString() {
            return "authCode={" + authCode + "}; resultStatus={" + resultStatus + "}; memo={" + memo + "}; result={" + result + "}";
        }

        private String getValue(String header, String data) {
            return data.substring(header.length(), data.length());
        }

        /**
         * @return the resultStatus
         */
        public String getResultStatus() {
            return resultStatus;
        }

        /**
         * @return the memo
         */
        public String getMemo() {
            return memo;
        }

        /**
         * @return the result
         */
        public String getResult() {
            return result;
        }

        /**
         * @return the resultCode
         */
        public String getResultCode() {
            return resultCode;
        }

        /**
         * @return the authCode
         */
        public String getAuthCode() {
            return authCode;
        }

        /**
         * @return the alipayOpenId
         */
        public String getAlipayOpenId() {
            return alipayOpenId;
        }
    }
}
